package com.xc.h05.service.weichen.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xc.h05.entity.Question;
import com.xc.h05.entity.User;
import com.xc.h05.mapper.QuestionMapper;
import com.xc.h05.mapper.ReplyMapper;
import com.xc.h05.mapper.UserMapper;
import com.xc.h05.service.weichen.QuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class QuestionServiceImpl implements QuestionService {
    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ReplyMapper replyMapper;
    @Override
    public int add(Question question) {
        question.setCreateTime(new Date());
        int add = questionMapper.add(question);
        return add;
    }

    @Override
    public int delete(int id) {
        int delete = questionMapper.delete(id);
        return delete;
    }

    @Override
    public int deletes(List list) {
        int deletes = questionMapper.deletes(list);
        return deletes;
    }

    @Override
    public int update(Question question) {
        int update = questionMapper.update(question);
        return update;
    }

    @Override
    public PageInfo<Question> findByPage(int pageNum, int pageSize, Question question) {
        PageHelper.startPage(pageNum,pageSize);
        List<Question> list = questionMapper.findByPage(question);
        for (Question qs : list) {
            User user = userMapper.findById(qs.getUserId());
            qs.setUser(user);
            int answerCount = replyMapper.findById(qs.getId());
            qs.setAnswerCount(answerCount);
        }
        PageInfo<Question> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public Question findById(int id) {
        Question question = questionMapper.findById(id);
        User user = userMapper.findById(question.getUserId());
        question.setUser(user);
        return question;
    }

    @Override
    public List<Question> findAll() {
        List<Question> list = questionMapper.findAll();
        for (Question qs : list) {
            User user = userMapper.findById(qs.getUserId());
            qs.setUser(user);
            int answerCount = replyMapper.findById(qs.getId());
            qs.setAnswerCount(answerCount);
        }
        return list;
    }
}
